const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
// 云函数入口函数
//点击接单
exports.main = async (event, context) => {
  const openid = cloud.getWXContext().OPENID
  var commonid = event.id;
  var _updateTime = new Date().getTime()
  var orderNum =String(_updateTime)+String(Math.random()).substr(3,8)
    var count = await db.collection("jf_dan").where({
      openid,
      commonid
    }).count()
    if(count.total){
      //已经接单
       await db.collection("jf_dan").where({
        openid,
        commonid
      }).remove()
     return await db.collection('jf_info').where({
        _id:commonid
      }).update({
        data:{
          ispick:false,
          state:1,
          getopenid:0
        }
      })
    }
    else{
        await db.collection("jf_dan").add({
        data:{
            commonid,
            openid,
            _updateTime
          }
         })
         return await db.collection('jf_info').where({
          _id:commonid
        }).update({
          data:{
            ispick:true,
            state:2,
            getopenid:openid
          }
        })
    }
  
   
}